﻿using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TR.Domain.Entity;
using TR.Domain.Entity.Permission;
using TR.Domain.Entity.roles;
using TR.Domain.Repository.rbac_UserRepository;

namespace TR.EFCore.Repository.rbac_UserRepository
{
    public class rbac_UserRepository : Irbac_UserRepository
    {

        private readonly MyContext context;

        public rbac_UserRepository(MyContext context)
        {
            this.context = context;
        }
        //权限拿取
        public async Task<List<Trees>> TreesSelects()
        {
            using (SqlConnection connection = new SqlConnection(context.conStr))
            {
                //不是吧老弟你要读取所有的权限数据啊
                string sql = "select [u_juriid],[u_jurname],[u_jurpid]\r\nfrom [dbo].[rbac_Jurisdiction]";
                List<Domain.Entity.rbac_Jurisdiction> quans = connection.Query<Domain.Entity.rbac_Jurisdiction>(sql).ToList();
                //2 把权限数据转换为层级结构数据
                List<Trees> trees = GetChild(quans, 0);
                return trees;
            }
        }
        private List<Trees> GetChild(List<Domain.Entity.rbac_Jurisdiction> quans, int v)
        {
            List<Trees> trees = new List<Trees>();
            List<Domain.Entity.rbac_Jurisdiction> Pquans = quans.Where(e => e.u_jurpid == v).ToList();
            foreach (Domain.Entity.rbac_Jurisdiction item in Pquans)
            {
                Trees trees1 = new Trees()
                {
                    Id = item.u_juriid,
                    authName = item.u_jurname
                };
                trees1.children = GetChild(quans, item.u_juriid);
                trees.Add(trees1);
            }
            return trees;
        }

        //根据登录名查询用户信息
        public async Task<rbac_User> UserSelect(string uname)
        {
            var result = await context.rbac_User.Where(p => p.U_UserName == uname).FirstOrDefaultAsync();

            return result;
        }

        public async Task<List<rolesuser>> UserSelects()
        {
            using (var con = new SqlConnection(context.conStr))
            {
                string sql = "SELECT ur.*, r.* FROM rbac_UserRoles ur INNER JOIN rbac_Roles r ON ur.U_rolesID = r.u_rolesid;";

                try
                {
                    await con.OpenAsync(); // 打开连接也是异步的  
                    var Rolo = await con.QueryAsync<rolesuser>(sql); // 等待查询完成  
                    return Rolo.ToList(); // 将IEnumerable<rolesuser>转换为List<rolesuser>  
                }
                catch (Exception ex)
                {
                    // 处理异常，例如记录日志或返回错误信息  
                    throw; // 或者你可以重新抛出异常，或者返回一个错误消息等  
                }
            }
        }
    }
}
